package pisa;

import yarp.Network;
import yarp.Bottle;
import yarp.Port;

/**
 * Hello world!
 *
 */
public class YarpListen {

    PisaApp app;
    String os;
    Bottle bot;
    Port reader;

    public YarpListen(PisaApp app, String os) {
        System.out.println("Yarp Listen constructor");
        this.os = os;
        this.app = app;
        if (os.equals("linux")) {
            System.load("/home/samf/yarp/bindings/build/libjyarp.so");
        } else if (os.equals("windows")) {
            System.loadLibrary("jyarp");
        }
        Network.init();

        reader = new Port();
        reader.open("/ZenoRobot/action:i");
        Network.connect("/ASAPRealizer/action:o", "/ZenoRobot/action:i");
        
        bot = new Bottle();
    }
    void start() {
        YarpLoop loop = new YarpLoop(this, reader, bot);
        loop.start();
  
    }
    void close() {
        reader.close();
    }
    
    void performAction(Bottle bot) {
        app.doAction(bot);
    }

}

class YarpLoop extends Thread {
    YarpListen listen;
    Port reader;
    Bottle bot;
    public YarpLoop(YarpListen listen, Port reader, Bottle bot) {
        this.listen = listen;
        this.reader = reader;
        this.bot = bot;
    }
     public void run() {
        while (true) {
            if (reader.read(bot)) {
                //System.out.println(word);
                System.out.println("Reading " + bot);
                listen.performAction(bot);
            }
        }
    }

}